package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerProductDetail;
import com.crm.model.entity.customerManager.CustomerProductDetailMemberCard;
import com.crm.model.entity.customerManager.CustomerProductDetailThroughTrainTax;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.model.vo.systemManager.MemberShipCardImportVO;
import com.crm.model.vo.systemManager.TaxCardImportVO;
import com.crm.service.common.DictionaryDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerProductDetailMemberCardDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:baijian
 * @Date: 2021/6/26 9:19
 */
@Slf4j
public class InsertTaxCardCallable implements Callable<JSONObject> {



    private CustomerDbService customerDbService;
    private UserAccountDbService userAccountDbService;
    private CustomerProductOrderDbService customerProductOrderDbService;
    private FinishOrderDBservice finishOrderDBservice;
    private List<TaxCardImportVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private String companyId;

    public InsertTaxCardCallable(CustomerDbService customerDbService, UserAccountDbService userAccountDbService,
                                 CustomerProductOrderDbService customerProductOrderDbService,
                                 FinishOrderDBservice finishOrderDBservice,
                                 List<TaxCardImportVO> list, CountDownLatch begin, CountDownLatch end, String companyId) {
        this.customerDbService = customerDbService;
        this.userAccountDbService = userAccountDbService;
        this.customerProductOrderDbService = customerProductOrderDbService;
        this.finishOrderDBservice = finishOrderDBservice;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.companyId = companyId;
    }

    @SneakyThrows
    @Override
    public JSONObject call() {
        //导入数量
        int importNum = 0;
        //修改的
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        List<Integer> importFailIdStr = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        Date updateDate = new Date();

        for (int i = 0; i < list.size(); i++) {
            TaxCardImportVO importVO = list.get(i);

            try {
                if(!StringUtils.isBlank(importVO.getTrainTax())) {
                    List<CustomerProductDetailThroughTrainTax> list = trainTaxSub(importVO.getTrainTax());
                    if(list != null && list.size() > 0) {
                        for(CustomerProductDetailThroughTrainTax tax : list) {
                            List<CustomerProductDetailThroughTrainTax> tList = customerDbService.selectTaxNumber(tax.getMemberCardNumber());
                            if(tList != null && tList.size() > 0){
                                CustomerProductDetailThroughTrainTax tra = tList.get(0);
                                tra = assembleTax(tra,importVO,updateDate,1);
                                if(!"1".equals(tra.getThroughTrainTaxId())){
                                    customerDbService.updateCustomerProductDetailThroughTrainTax(tra);
                                    repeatIdStr.add(i+2);
                                }
                            }else{
                                tax.setThroughTrainTaxId(CommonUtils.getGUID());
                                tax = assembleTax(tax,importVO,updateDate,2);
                                customerDbService.addCustomerProductDetailThroughTrainTax(tax);
                                importNum = importNum + 1;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                importFailIdStr.add(i+2);
                log.error("导入直通车异常, Exception info : {}", e);
            }
        }

        jsonObject.put("importNum",importNum);
        jsonObject.put("repeatIdStr",repeatIdStr);
        jsonObject.put("importFailIdStr",importFailIdStr);
        return jsonObject;
    }

    /**
     *组装参数
     * @param tax
     * @param importVO
     * @param updateDate 修改时间
     * @param bs 1修改 2新增
     * @return
     */
    public CustomerProductDetailThroughTrainTax assembleTax(CustomerProductDetailThroughTrainTax tax,TaxCardImportVO importVO,Date updateDate,Integer bs) {
        if(2 == bs) {
            if(!StringUtils.isBlank(importVO.getCreateTm())) {
                Date createTm = formatTimeSf(importVO.getCreateTm());
                if(!StringUtils.isBlank(importVO.getAccountName())) {
                    UserAccount userAccount = userAccountDbService.selectUserAccountByUserName(importVO.getAccountName());
                    if (userAccount != null) {
                        tax.setCreatePeopleId(userAccount.getAccountId());
                        tax.setCreateTm(createTm);
                        tax.setUpdatePeopleId(userAccount.getAccountId());
                        tax.setUpdateTm(updateDate);
                        tax.setCompanyId(userAccount.getCompanyId());
                        tax.setDataSource(1);
                    }

                    if (!StringUtils.isBlank(importVO.getOrderNumber())) {
                        CustomerProductOrderVO order = customerProductOrderDbService.getOrderInfoByNumber(importVO.getOrderNumber());
                        if (order != null) {
                            tax.setProductOrderId(order.getProductOrderId());
                            List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1", "1", order.getProductOrderId());
                            if (finishOrderProductList != null && finishOrderProductList.size() > 0) {
                                FinishOrderProduct fin = finishOrderProductList.get(0);
                                tax.setProductCode(fin.getProductCode());
                                tax.setFinishOrderProductNum(fin.getFinishOrderProductNum());
                            }
                        }
                    }
                }
            }
        }else{

            if(StringUtils.isBlank(tax.getProductOrderId())) {
                if (!StringUtils.isBlank(importVO.getOrderNumber())) {
                    CustomerProductOrderVO order = customerProductOrderDbService.getOrderInfoByNumber(importVO.getOrderNumber());
                    if (order != null) {
                        tax.setProductOrderId(order.getProductOrderId());
                        List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1", "1", order.getProductOrderId());
                        if (finishOrderProductList != null && finishOrderProductList.size() > 0) {
                            FinishOrderProduct fin = finishOrderProductList.get(0);
                            tax.setProductCode(fin.getProductCode());
                            tax.setFinishOrderProductNum(fin.getFinishOrderProductNum());
                        }
                    }
                }
                tax.setUpdateTm(updateDate);
            }else{
                tax.setThroughTrainTaxId("1");
            }
        }

        return tax;
    }




    public static void main(String[] args) {
        List<CustomerProductDetailThroughTrainTax> list = trainTaxSub("用户名:1517953\t密码:17782218;\n" +
                "用户名:1517954\t密码:99819250");
        for(CustomerProductDetailThroughTrainTax tax : list) {
            System.out.println("卡号:"+tax.getMemberCardNumber() + " 密码:" + tax.getMemberCardPassword());
            System.out.println("-----------------------------");
        }
    }

    /**
     * 税法直通车 切割参数
     * @param trainTax
     * @return
     */
    public static List<CustomerProductDetailThroughTrainTax> trainTaxSub(String trainTax) {
        List<CustomerProductDetailThroughTrainTax> list = new ArrayList<>();
        if(trainTax.contains("卡号:")) {
            if(trainTax.contains(";")) {
                String[] split = trainTax.split(";");
                for(String a : split) {
                    CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
                    String num = a.substring(a.indexOf("卡号:")+3,a.indexOf("密码:"));
                    String password = a.substring(a.indexOf("密码:")+3,a.length());
                    tax.setMemberCardNumber(num);
                    tax.setMemberCardPassword(password);
                    list.add(tax);
                }
            }else{
                CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
                String num = trainTax.substring(trainTax.indexOf("卡号:")+3,trainTax.indexOf("密码:"));
                String password = trainTax.substring(trainTax.indexOf("密码:")+3,trainTax.length());
                tax.setMemberCardNumber(num);
                tax.setMemberCardPassword(password);
                list.add(tax);
            }
        } else if(trainTax.contains("用户名：")) {
            trainTax = trainTax.replaceAll("\t|\n","");
            if(trainTax.indexOf("用户名：",2) != -1){
                String[] split = trainTax.split("用户名：");
                for(String a : split) {
                    if(!StringUtils.isBlank(a)) {
                        CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
                        String num = a.substring(0,a.indexOf("密码"));
                        String password = a.substring(a.indexOf("密码")+3,a.length());
                        tax.setMemberCardNumber(num);
                        tax.setMemberCardPassword(password);
                        list.add(tax);
                    }
                }
            }else{
                CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
                String num = trainTax.substring(4,trainTax.indexOf("密码"));
                String password = trainTax.substring(trainTax.indexOf("密码")+3,trainTax.length());
                tax.setMemberCardNumber(num);
                tax.setMemberCardPassword(password);
                list.add(tax);
            }
        } else if(!trainTax.contains("卡号:") && !trainTax.contains("用户名：")) {
            if(trainTax.contains(";")) {
                String[] split = trainTax.split(";");
                for(String a : split) {
                    CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
                    String num = a.substring(0,a.indexOf(":"));
                    String password = a.substring(a.indexOf(":")+1,a.length());
                    tax.setMemberCardNumber(num);
                    tax.setMemberCardPassword(password);
                    list.add(tax);
                }
            }else{
                CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
                String num = trainTax.substring(0,trainTax.indexOf(":"));
                String password = trainTax.substring(trainTax.indexOf(":")+1,trainTax.length());
                tax.setMemberCardNumber(num);
                tax.setMemberCardPassword(password);
                list.add(tax);
            }
        } else {
            CustomerProductDetailThroughTrainTax tax = new CustomerProductDetailThroughTrainTax();
            tax.setMemberCardNumber(trainTax);
            list.add(tax);
        }

        return list;
    }


    /**
     * 转时间格式
     * @param date 创建时间  结束时间
     * @return
     */
    public Date formatTime(String date) throws ParseException {
        //同一个Excel有不一样的时间格式……
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(date);
    }

    /**
     * 转时间格式
     * @param date 创建时间  结束时间
     * @return
     */
    public Date formatTimeSf(String date) {
        try{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return simpleDateFormat.parse(date);
        }catch(Exception e) {
            e.printStackTrace();
        }
        return null;
        //同一个Excel有不一样的时间格式……
    }

    /*public static void main(String[] args) {
        String a = "武汉东湖新技术开发区高新二路388号光谷国际生物医药企业加速器一期工程1号厂房C1-1-0283自贸区武汉片区";
        //String[] split = a.split(",");
        System.out.println(a.length());
    }*/
}
